package pl.edu.pw.MidEmu.UI.Controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JCheckBox;

import pl.edu.pw.MidEmu.Base.Controllers.BaseController;
import pl.edu.pw.MidEmu.Common.Consts;
import pl.edu.pw.MidEmu.Common.Models.EthernetInterfaceModel;
import pl.edu.pw.MidEmu.Logic.EthernetService;
import pl.edu.pw.MidEmu.Logic.ProcessHandler;
import pl.edu.pw.MidEmu.UI.Views.NetworkSettingsView;

/**
 * Controller for managing network interfaces
 * @author Mateusz Starodab
 *
 */
public class NetworkSettingsController extends BaseController<NetworkSettingsView> implements ActionListener
{
	private EthernetService _ethernetService;

	public NetworkSettingsController()
	{
		_ethernetService = new EthernetService();
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() instanceof JButton)
		{
			JButton button = (JButton) e.getSource();
			if (button.getName() == Consts.NetworkSettings_ButtonAdd)
			{
				ProcessHandler h = new ProcessHandler("./data/addInterface " + _ethernetService.getTapAddressesCount(), "", "");
				h.start();
				getView().refresh();
			}
			else if (button.getName() == Consts.NetworkSettings_ButtonCancel)
			{
				getView().dispose();
			}
			else if (button.getName() == Consts.NetworkSettings_ButtonRefresh)
			{
				getView().refresh();
			}
		}
		else if (e.getSource() instanceof JCheckBox)
		{
			JCheckBox box = (JCheckBox) e.getSource();
			if (box.getModel().isSelected())
				getView().registerIface(_ethernetService.getIfaceByName(box.getName()));
			else
				getView().unregisterIface(box.getName());
		}
	}

	public List<EthernetInterfaceModel> getEthernetInterfaces()
	{
		return _ethernetService.getAviableEthernetInterfaces();
	}

}
